package cn.itsource.ymcc.mq;

import cn.itsource.ymcc.constant.ErrorConstantCode;
import cn.itsource.ymcc.constant.MQConstants;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.domain.CourseOrderItem;

import cn.itsource.ymcc.dto.NotifyPayMsgDto;
import cn.itsource.ymcc.exception.GlobalException;
import cn.itsource.ymcc.service.ICourseOrderService;
import cn.itsource.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@RocketMQMessageListener(
        consumerGroup = MQConstants.TX_PAY_NOTIFY_COMSUMER_GROUP,
        topic = MQConstants.TX_PAY_NOTIFY_TOPIC,
        selectorExpression = "*",
        messageModel = MessageModel.BROADCASTING //广播，所有的消费者都要能消费回调消息

)
@Service
@Slf4j
public class NotifyPayMessageLinster implements RocketMQListener<MessageExt> {

    @Autowired
    private ICourseOrderService courseOrderService;

    @Override
    public void onMessage(MessageExt messageExt) {
        log.info("收到修改订单状态的消息：{}",messageExt);
        NotifyPayMsgDto msgDto = null;
        try{
            byte[] body = messageExt.getBody();
            String jsonStr = new String(body, StandardCharsets.UTF_8);
            msgDto = JSON.parseObject(jsonStr, NotifyPayMsgDto.class);

        }catch (Exception e){
            e.printStackTrace();
            throw new GlobalException("消费回调通知异常！");
        }

        AssertUtil.isNotNull(msgDto, ErrorConstantCode.PARAMETER_NOT_BE_NULL);
        log.info("修改订单状态：{}",msgDto);

        String orderNo = msgDto.getOrderNo();

        synchronized (orderNo){
            Wrapper<CourseOrder> wrapper = new EntityWrapper<>();
            wrapper.eq("order_no",orderNo);
            CourseOrder courseOrder = courseOrderService.selectOne(wrapper);
            AssertUtil.isNotNull(courseOrder,ErrorConstantCode.PARAMETER_NOT_BE_NULL);

            log.info("修改订单状态,订单：{}",courseOrder);

            Integer statusOrder = courseOrder.getStatusOrder();

            if(CourseOrder.OK_PAY == statusOrder){
                //已经支付过了，之前有并发操作实现
                return;
            }


            if(CourseOrder.NO_PAY == statusOrder){
                // 原来的状态是未支付，要修改
                courseOrder.setStatusOrder(msgDto.getPayStatus());
                courseOrderService.updateById(courseOrder);
                log.info("完成，修改订单状态");
            }

            if(CourseOrder.CANCEL_PAY == statusOrder){
                // 订单以取消（超时关闭！），但是用户支付成功！！
                // 需要调用支付服务，发起退款操作！
            }

        }

    }
}
